package cn.lzj.basic.service.impl;

import cn.lzj.basic.constants.VerifyCodeConstants;
import cn.lzj.basic.dto.BinderDto;
import cn.lzj.basic.dto.LoginDto;
import cn.lzj.basic.exception.BusinessException;
import cn.lzj.basic.jwt.JwtUtils;
import cn.lzj.basic.jwt.LoginData;
import cn.lzj.basic.jwt.RsaUtils;
import cn.lzj.basic.service.ILoginDtoService;
import cn.lzj.basic.util.AjaxResult;
import cn.lzj.basic.util.HttpClientUtils;
import cn.lzj.basic.util.MD5Utils;
import cn.lzj.basic.util.StrUtils;
import cn.lzj.system.domain.Menu;
import cn.lzj.user.domain.Logininfo;
import cn.lzj.user.domain.User;
import cn.lzj.user.domain.Wxuser;
import cn.lzj.user.mapper.LogininfoMapper;
import cn.lzj.user.mapper.UserMapper;
import cn.lzj.user.mapper.WxuserMapper;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class LoginDtoServiceImpl implements ILoginDtoService {
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate redisTemplate;

    @Override
    public Map<String, Object> account(LoginDto loginDto) {
        //1.空值校验
        String password = loginDto.getPassword();
        String username = loginDto.getUsername();
        Integer type = loginDto.getType();
        if (StringUtils.isEmpty(password) ||
                StringUtils.isEmpty(username) ||
                StringUtils.isEmpty(type)) {
            throw new BusinessException("参数不能为空或异常！！！");
        }
        //2.根据username+type判断密码是否正确
        Logininfo logininfo = logininfoMapper.loadByloginDto(loginDto);
        if (logininfo == null) {
            throw new BusinessException("账号不存在！！！");
        }
        //3.判断密码是否一致
        String salt = logininfo.getSalt();
        String md5Pwd = MD5Utils.encrypByMd5(loginDto.getPassword() + salt);
        if (!md5Pwd.equals(logininfo.getPassword())) {
            throw new BusinessException("密码错误！！");
        }
        //4.是否被禁用
        Boolean disable = logininfo.getDisable();
        if (!disable) {
            throw new BusinessException("您的账号被禁用！！请联系管理员");
        }
        //5.将登录信息存储到redis中  注意：对象需要实现序列化接口  implements Serializable
/*        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(token, logininfo,
                30, TimeUnit.MINUTES);
        //6.返回token和logininfo
        Map<String, Object> map = new HashMap<>();
        //可以将salt和passwrod置空
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("token", token);
        map.put("logininfo", logininfo);*/
        Map<String, Object> map= loginSuccessJwtHandler(logininfo);
        return map;
    }
     public Map<String, Object> loginSuccessJwtHandler(Logininfo logininfo){
         LoginData loginData = new LoginData();
         logininfo.setSalt(null);
         logininfo.setPassword(null);
         loginData.setLogininfo(logininfo);
         //装到map
         Map<String, Object> map = new HashMap<>();
         try {
             if(logininfo.getType() ==0){
                 //1.根据logininfo查询出登录者的所有
                 List<String> permissions = logininfoMapper.loadPerssionSnByLogininfoId(logininfo.getId());
                 List<Menu> menus = logininfoMapper.loadMenuByLogininfoId(logininfo.getId());
                 loginData.setPermissions(permissions);
                 loginData.setMenus(menus);
                 map.put("permissions",permissions);
                 map.put("menus", menus);
             }
             PrivateKey privateKey = RsaUtils.getPrivateKey(RsaUtils.class.getClassLoader().getResource("auth_rsa.pri").getFile());
             String jwtToken = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 30);
             map.put("token",jwtToken);
             map.put("logininfo",logininfo);
             return map;
         } catch (Exception e) {
             e.printStackTrace();
         }
         return null;
     }
    @Override
    public Map<String, Object> useraccount(LoginDto loginDto) {
        //1.空值校验
        String password = loginDto.getPassword();
        String username = loginDto.getUsername();
        Integer type = loginDto.getType();
        if (StringUtils.isEmpty(password) ||
                StringUtils.isEmpty(username) ||
                StringUtils.isEmpty(type)) {
            throw new BusinessException("参数不能为空或异常！！！");
        }
        //2.根据username+type判断密码是否正确
        Logininfo logininfo = logininfoMapper.loadByloginDto(loginDto);
        if (logininfo == null) {
            throw new BusinessException("账号不存在！！！");
        }
        //3.判断密码是否一致
        String salt = logininfo.getSalt();
        String md5Pwd = MD5Utils.encrypByMd5(loginDto.getPassword() + salt);
        if (!md5Pwd.equals(logininfo.getPassword())) {
            throw new BusinessException("密码错误！！");
        }
        //4.是否被禁用
        Boolean disable = logininfo.getDisable();
        if (!disable) {
            throw new BusinessException("您的账号被禁用！！请联系管理员");
        }
        //5.将登录信息存储到redis中  注意：对象需要实现序列化接口  implements Serializable
        Map<String, Object> map= loginSuccessJwtHandler(logininfo);
        return map;
    }

    @Override
    public AjaxResult wechat(String code) {
        //1.接收code，做校验
        //让springmvc帮我把code转成字符串
        String tokenUrl = VerifyCodeConstants.LoginConstants.TOKEN_URL
                .replace("APPID", VerifyCodeConstants.LoginConstants.APPID)
                .replace("SECRET", VerifyCodeConstants.LoginConstants.SECRET)
                .replace("CODE", code);

        //2.根据code从微信去获取token + openId
        String josnStr = HttpClientUtils.httpGet(tokenUrl);
        //josnStr是json的字符串  转化成json对象--fastjson
        JSONObject jsonObject = JSONObject.parseObject(josnStr);
        String access_token = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");
        //3.根据openId查询本地的t_wxuser，看是否曾今已经扫码过
        Wxuser wxuser = wxuserMapper.loadByOpenId(openid);
        if (wxuser != null && wxuser.getUser_id() != null) {
            //3.1. 有值且t_wxuser表中的user_id有值 曾今已经扫过，本次是第二...N扫码
            //必须查询logininfoTmp
            Logininfo logininfo = logininfoMapper.loadbyUserId(wxuser.getUser_id());
            Map<String, Object> map= loginSuccessJwtHandler(logininfo);
            return AjaxResult.util().setsuccess(true).setResultObj(map);
        } else {
            //        直接免密登录
            //3.2. 没有，需要走微信绑定流程
            HashMap<String, Object> map = new HashMap<>();
            map.put("access_token",access_token);
            map.put("openid",openid);
            return AjaxResult.util().setsuccess(false).setResultObj(map);
        }
    }
    @Override
    public AjaxResult binder(BinderDto binderDto) {
        String phone = binderDto.getPhone();
        String verifyCode = binderDto.getVerifyCode();
        String accessToken = binderDto.getAccessToken();
        String openId = binderDto.getOpenId();
        //1.校验空值
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(verifyCode)) {
            throw new BusinessException("所填信息不能为空！！");
        }
        //2.校验：验证码是否过期
        Object redisBinderphone = redisTemplate.opsForValue().get(VerifyCodeConstants.BINDER_PREFIX + phone);
        if (redisBinderphone == null) {
            throw new BusinessException("验证码失效,请重新获取!!!");
        }//判断验证码是否正确
        String binderCode = redisBinderphone.toString().split(":")[0];
        if (!binderCode.equals(verifyCode)) {
            throw new BusinessException("验证码错误!!!");
        }
        //4.绑定用户：t_wxuser【user_id】 绑定t_user
        //获取Wxuser - 发送第三个请求  - json字符串
        String url = VerifyCodeConstants.LoginConstants.USER_URL
               .replace("ACCESS_TOKEN", accessToken)
               .replace("OPENID", openId);
        String jsonStr = HttpClientUtils.httpGet(url);
        Wxuser wxuser = jsonStr2Wxuser(jsonStr);
        //5.通过phone查询User
        User user = userMapper.loadByphone(phone);
        //5.1如果没有 --根据phone创建的 user对象
        if (user == null) {
            user = phone2User(phone);
            //5.2创建logininfo对象
            Logininfo logininfo = user2Logininfo(user);
            logininfoMapper.save(logininfo);
            user.setLogininfoId(logininfo.getId());
            //5.3保存logininfo对象 -- 保存User对象
            userMapper.save(user);
        }
        //6.将Wxuser对象的id设置到Wxuser对象中
        wxuser.setUser_id(user.getId());
        //7.将Wxuser对象添加到数据库
        wxuserMapper.save(wxuser);
        //8.免密登录逻辑
        Logininfo logininfo = logininfoMapper.loadbyUserId(wxuser.getUser_id());
        Map<String, Object> map= loginSuccessJwtHandler(logininfo);
        return AjaxResult.util().setResultObj(map);
    }

    @Override
    public AjaxResult logout(String token) {
        redisTemplate.delete(token);
        return AjaxResult.util().setsuccess(true).setmessage("退出成功!!");

    }

    private Wxuser jsonStr2Wxuser(String jsonStr) {
        Wxuser wxuser = new Wxuser();
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        wxuser.setOpenid(jsonObject.getString("openid"));
        wxuser.setNickname(jsonObject.getString("nickname"));
        wxuser.setSex(jsonObject.getInteger("sex"));
        wxuser.setAddress(jsonObject.getString("country") +
        jsonObject.getString("province") + jsonObject.getString("city"));
        wxuser.setHeadimgurl(jsonObject.getString("headimgurl"));
        wxuser.setUnionid(jsonObject.getString("unionid"));
        return wxuser;
    }
    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user, logininfo);
        logininfo.setType(1);
        return logininfo;
    }
    private User phone2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getRandomString(32);
        //获取随机六位数密码
        String randomPwd = StrUtils.getRandomString(6);
        String md5Pwd = MD5Utils.encrypByMd5(randomPwd + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        return user;
    }
}
